package com.yangzb.spring.batch;

import cn.hutool.extra.spring.SpringUtil;
import com.yangzb.spring.batch.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.database.*;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.database.builder.JdbcPagingItemReaderBuilder;
import org.springframework.batch.item.database.support.SqlPagingQueryProviderFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Map;


@Configuration
@Slf4j
public class BatchConfig {
    public BatchConfig(){
        DataSourceProperties dataSourceProperties = new DataSourceProperties();
        dataSourceProperties.setUrl("jdbc:mysql://192.168.10.159:3308/yzb_test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&rewriteBatchedStatements=true&serverTimezone=GMT%2B8&useSSL=false");
        dataSourceProperties.setUsername("root");
        dataSourceProperties.setPassword("rootPWD!@#");
        try {
            SpringUtil.registerBean("ds1",DataSourceUtils.create(dataSourceProperties));
        } catch (Exception e) {
            log.error("",e);
        }
    }
    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

//    @Qualifier("dataSource")
    public DataSource dataSource;
    //    @Autowired
//    private ItemReaderService itemReaderService;
//    @Autowired
//    private ItemReaderService2 itemReaderService2;
    @Autowired
    private ItemProcessorService itemProcessorService;
//    @Autowired
//    private ItemProcessorService2 itemProcessorService2;
//    @Autowired
//    private ItemWriterService itemWriterService;
//    @Autowired
//    private JdbcPagingItemReader jdbcPagingItemReader;
    @Autowired
    private ItemWriterService itemWriterService;
    @Autowired
    private JobListener jobListener;


//    @Bean
//    public Job singleStepJob(JdbcPagingItemReader jdbcPagingItemReader) {
//        return jobBuilderFactory.get("singleStepJob")
//                .incrementer(new RunIdIncrementer())
//                .listener(listener())
//                .start(uppercaseStep(jdbcPagingItemReader))
//                .build();
//    }

    @Bean
    public Job cStepJob() {
        return jobBuilderFactory.get("cStepJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener())
                .start(cStep())
                .build();
    }

//    @Bean
//    public Job multiBoundStepsJob() {
//        return jobBuilderFactory.get("multiBoundStepsJob")
//                .incrementer(new RunIdIncrementer())
//                .listener(listener())
//                .start(uppercaseStep())
//                .next(addMessageStep())
//                .build();
//    }
    @Bean
    public Step cStep() {
        return stepBuilderFactory.get("cStep")
                .<Map, Map>chunk(1000)
                .reader(jdbcReader())
    //                .processor(itemProcessorService)
                .writer(itemWriter())
                .listener(new MItemWriteListener(ds1()))
                .build();
    }


//    @Bean
//    public Step dStep() {
//        return stepBuilderFactory.get("step2")
//                .tasklet(task)
//                .build();
//    }
//    @Bean
//    public Step uppercaseStep(JdbcPagingItemReader jdbcPagingItemReader) {
//        return stepBuilderFactory.get("uppercaseStep")
//                .<Map, Map>chunk(500)
//                .reader(jdbcReader())
////                .processor(itemProcessorService)
//                .writer(itemWriter()).build();
//    }
//    @Bean("dataSource")
//    @Primary
//    @ConfigurationProperties(prefix = "spring.datasource")
//    public DataSource dataSource() {
//        return DataSourceBuilder.create().build();
//    }
    @Bean
    public SqlPagingQueryProviderFactoryBean queryProvider() {
        SqlPagingQueryProviderFactoryBean provider = new SqlPagingQueryProviderFactoryBean();
        provider.setDataSource(ds1());
        provider.setSelectClause("select *");
        provider.setFromClause("from contact_order_1100");
        provider.setSortKey("CONTACT_ORDER_ID");
        return provider;
    }


//    @Bean("ds1")
    public DataSource ds1(){
//        DataSourceProperties dataSourceProperties = new DataSourceProperties();
//        dataSourceProperties.setUrl("jdbc:mysql://192.168.10.159:3308/yzb_test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&rewriteBatchedStatements=true&serverTimezone=GMT%2B8&useSSL=false");
//        dataSourceProperties.setUsername("root");
//        dataSourceProperties.setPassword("rootPWD!@#");
        return SpringUtil.getBean("ds1");
    }

    @Bean
    public JdbcCursorItemReader<Map> jdbcReader() {
        JdbcCursorItemReader<Map> jcir = new JdbcCursorItemReader();
        jcir.setDataSource(ds1());
        jcir.setRowMapper(new JdbcRowMapper());
        jcir.setFetchSize(2000);
//        jcir.setMaxItemCount(2000);
//        jcir.setMaxRows(2000);
        jcir.setSql("select * from contact_order_1100_3");
        return jcir;
    }

    @Bean
    public JdbcBatchItemWriter<Map> itemWriter() {
        JdbcBatchItemWriterBuilder<Map> jdbcBatchItemWriterBuilder = new JdbcBatchItemWriterBuilder<Map>();
        jdbcBatchItemWriterBuilder//.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<Map>())
                .sql("INSERT INTO contact_order_1100_2(CONTACT_ORDER_ID,MKT_CAMPAIGN_ID,CONTACT_TASK_ID,TARGET_OBJ_TYPE,WAVE_NAME,WAVE_ID,TARGET_OBJ_NBR,EVT_INST_ID,\n" +
                        "PRIORITY_ACC_NBR,ACC_NBR,CUST_NAME,CONTACT_CHL_ID,CONTACT_STAFF,REGION_ID,CONTACT_OBJ_TYPE,CONTACT_OBJ_ID,SEND_DATE,\n" +
                        "STATUS_CD,CREATE_STAFF,UPDATE_STAFF,CREATE_DATE,STATUS_DATE,UPDATE_DATE,REMARK) \n" +
                        "VALUES (:CONTACT_ORDER_ID,:MKT_CAMPAIGN_ID,:CONTACT_TASK_ID,:TARGET_OBJ_TYPE,:WAVE_NAME,:WAVE_ID,:TARGET_OBJ_NBR,:EVT_INST_ID,\n" +
                        ":PRIORITY_ACC_NBR,:ACC_NBR,:CUST_NAME,:CONTACT_CHL_ID,:CONTACT_STAFF,:REGION_ID,:CONTACT_OBJ_TYPE,:CONTACT_OBJ_ID,:SEND_DATE,\n" +
                        ":STATUS_CD,:CREATE_STAFF,:UPDATE_STAFF,:CREATE_DATE,:STATUS_DATE,:UPDATE_DATE,:REMARK)")
                .dataSource(ds1());
        return jdbcBatchItemWriterBuilder.build();
    }


//    @Bean
//    public JdbcPagingItemReader<Map> itemReader(PagingQueryProvider queryProvider) {
//        JdbcPagingItemReaderBuilder<Map> jdbcPagingItemReaderBuilder = new JdbcPagingItemReaderBuilder<Map>().name("creditReader");
//        jdbcPagingItemReaderBuilder.name("creditReader");
//        jdbcPagingItemReaderBuilder.dataSource(dataSource);
//        jdbcPagingItemReaderBuilder.queryProvider(queryProvider);
//        jdbcPagingItemReaderBuilder.rowMapper(new JdbcRowMapper());
//        jdbcPagingItemReaderBuilder.pageSize(10000);
//        return jdbcPagingItemReaderBuilder.build();
//    }

//    @Bean
//    public Step addMessageStep() {
//        return stepBuilderFactory.get("addMessageStep")
//                .<String, String>chunk(1)
//                .reader(itemReaderService2)
//                .processor(itemProcessorService2)
//                .writer(itemWriterService).build();
//    }

    @Bean
    public JobExecutionListener listener() {
        return jobListener;
    }
}
